<?php
namespace app\api\controller;

use app\common\model\Cate as CateModel;
use app\common\model\Forum as ForumModel;
use app\common\validate\Forum as ForumValidate;

class Forum extends Base
{
	public function initialize()
	{
		parent::initialize();
		if((request()->action() != 'index' || request()->action() != 'read') && !$this->user){
			return cdm(401,0,'请先登录!');
		}
	}

	public function index()
	{
		$page = request_input('page',1);
		$pageSize = request_input('pageSize',20);
		$sort = request_input('sort',0);
		$param['keyword'] = request_input('keyword');
		$param['cate_id'] = request_input('cate_id',0);
		$param['user_id'] = request_input('user_id',0);
		$data = ForumModel::Nwhere($param)->whereOr(['top'=>3])->Norder($sort)->paginate($pageSize)->append(['user']);
		return cdm(200, $data, '');
	}

	public function create()
	{
		$page = request_input('page',1);
		$data = $this->user->forums()->order('id desc')->paginate(10);
		return cdm(200, $data, '');
	}

	public function save()
	{
		$data['cate_id'] = request_input('cate_id',0);
		$data['title'] = request_input('title','');
		$data['content'] = request_input('content','');
		$data['attachments'] = request_input('attachments',[]);
		$data['user_id'] = $this->user->id;

		$validate = new ForumValidate;
		if (!$validate->check($data)) {
			return cdm(500, 0, $validate->getError());
		}

		$cate = CateModel::get($data['cate_id']);
		if(!$cate){
			return cdm(500, 0, '版块不存在!');
		}
		if($cate->status == 0){
			return cdm(500, 0, '该版块不允许发帖!');
		}
		
		$this->user->forums()->save($data);
		$cate->save(['day_count'=>$cate->day_count + 1,'forum_count'=>$cate->forum_count + 1]);
		return cdm(200, 1, '发表成功!');
	}

	public function read($id)
	{
		$data = ForumModel::get($id);
		if($data){
			$data->append(['user','cate','attachments'=>['id','name','password','money','hits']]);
			$data->setInc('hits');
			if($this->user){
				$history = $this->user->historys()->where(['forum_id'=>$id])->find();
				if($history){
					$history->setInc('hits');
				}else{
					$this->user->historys()->save(['forum_id'=>$id]);
				}
			}
			return cdm(200, $data, '');
		}else{
			return cdm(500, 0, '数据不存在');
		}
	}

	public function edit($id)
	{
		
	}

	public function update($id)
	{
		$data['title'] = request_input('title','');
		$data['content'] = request_input('content','');
		$data['attachments'] = request_input('attachments',[]);

		$validate = new ForumValidate;
		if (!$validate->check($data)) {
			return cdm(500, 0, $validate->getError());
		}

		$forum = $this->user->forums()->get($id);
		if(!$forum){
			return cdm(500, 0, '数据不存在!');
		}
		$forum->save($data);
		return cdm(200, 1, '修改成功!');
	}

	public function delete($id)
	{
		$forum = $this->user->forums()->get($id);
		if(!$forum){
			return cdm(500, 0, '数据不存在!');
		}
		$ret = $forum->destroy($id);
		if($ret){
			return cdm(200, 1, '删除成功!');
		}
		return cdm(500, 0, '删除失败!');
	}
}